<?php

if (!defined('TOBBIVM'))
	header('location:/template/notrepassing.php');
/**
 * This file is part of TobbiVMShop.
 *
 * TobbiVMShop is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TobbiVMShop is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TobbiVMShop.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Verify and save data from article-editorpage and then call articlepage
 * used from article.page.php (article.page.editor.php)
 *
 * @version    $Id$
 * @package    TobbiVM-Shop
 * @copyright  Copyright (C) 2012
 * @author     Norbert Gebert
 * @license    GPL3
 */
$mysqlBuffer = array();
$newImage = false;
$newSmallImage = false;

$datax = $refValidate->testNumber($_POST['idx'], '');
if (!$datax)
{
	message::setErrorRow(_('ID-Number for saving has a wrong format or is invalid.') . '<br>' .
		_('No data could be saved!'), true);
}
else
{
	$idx = $datax;

	// sku
	$datax = $refValidate->testText($_POST['skux'], _('No SKU could be saved.'), 2, 64);
	if ($datax)
		$mysqlBuffer['product_sku'] = $datax;

	// articlename
	$namex = $refValidate->testText($_POST['namex'], _('No Productname could be saved.'), 2,
		64);
	if ($namex)
	{
		$mysqlBuffer['product_name'] = $namex;
		$artNamex = $idx . ' ' . $namex;
	}

	// category-id
	$datax = $refValidate->testNumber($_POST['categoryx'], _('No Categoryname could be saved.'));
	if ($datax)
	{
		$mysqlBuffer['product_category'] = intval($datax);
		$catIdx = $datax;
	}

	// activ
	if (isset($_POST['activex']))
	{
		$mysqlBuffer['product_active'] = '1';
	}
	else
	{
		$mysqlBuffer['product_active'] = '0';
	}

	// Article browsepage
	$datax = $refValidate->testText($_POST['browsepagex'],
		_('No Browsepage could be saved.'), 1);
	if ($datax)
		$mysqlBuffer['product_browsepage'] = $datax;

	// Article Attributelist
	$datax = $refValidate->testNumber($_POST['attributpagex'],
		_('No Attributepage could be saved.'));

	if ($datax >= 0)
		$mysqlBuffer['product_attribute_id'] = $datax;

	// short-desciption
	$mysqlBuffer['product_short_description'] = $_POST['shorttextx'];

	// description
	$mysqlBuffer['product_description'] = $_POST['textx'];

	// stocks_quantity
	$datax = $refValidate->testNumber($_POST['stocksx'], _('No Stockvalue could be saved.'));
	if ($datax)
		$mysqlBuffer['product_stocks_quantity'] = $datax;

	// tax_id
	$datax = $refValidate->testNumber($_POST['taxx'], _('No Tax-ID could be saved.'));
	if ($datax)
		$mysqlBuffer['product_tax_id'] = $datax;

	// Pricelist
	$ppricex = $refValidate->cleanslash($_POST['priceFixx'], _('Error in Price.'));
	$priceIdx = $refValidate->cleanslash($_POST['pricex'], _('Error in Price-ID.'));
	$ppricex = str_replace(',', '.', $ppricex);

	if (floatval($ppricex) > 0)
	{ // Only fixprice
		db::getInstance()->where('price_id', $priceIdx);
		db::getInstance()->where('price_list', $idx);
		$result = db::getInstance()->getOne('price');

		if (db::getInstance()->count <= 0)
		{ // New fixprice entry
			if (db::getInstance()->count <= 0)
			{
				$data = Array('price_art' => 1, 'price_list' => $idx, 'price_per_item' => $ppricex);
				db::getInstance()->insert('price', $data);

				db::getInstance()->where('price_list', $idx);
				$result = db::getInstance()->getOne('price');
				$priceIdx = $result['price_id'];
			}
		}
		else
		{ // Change entry
			db::getInstance()->where('price_id', $priceIdx);
			db::getInstance()->where('price_list', $idx);
			$data = Array('price_art' => 1, 'price_list' => $idx, 'price_per_item' => $ppricex);
			db::getInstance()->update('price', $data);
		}
	}
	else
	{
		db::getInstance()->where('price_id', $priceIdx);
		$data = Array('price_per_item' => 0);
		db::getInstance()->update('price', $data);
	}

	// set price_id
	$mysqlBuffer['product_price_id'] = $priceIdx;

	// Image
	$datax = $refValidate->cleanslash($_FILES['imagefile']['name']);
	$oldImagex = $refValidate->testText($_POST['oldImagex'], _('Article image'));
	if ($datax and ! empty($datax))
	{ // First delete old Image if available
		$file = '../images/' . ARTICLE_IMAGE_PATH . '/' . $catIdx .
			'/' . $oldImagex;

		if (!empty($oldImagex) and file_exists($file))
		{
			if (unlink('../images/' . ARTICLE_IMAGE_PATH . '/' . $catIdx . '/' .
					$oldImagex))
				message::setNoteRow(_('The old image file was replaced successfully.'));
		}

		if (!is_dir('../images/' . ARTICLE_IMAGE_PATH))
			mkdir('../images/' . ARTICLE_IMAGE_PATH);

		if (!is_dir('../images/' . ARTICLE_IMAGE_PATH . '/' . $catIdx))
			mkdir('../images/' . ARTICLE_IMAGE_PATH . '/' . $catIdx);

		include_once('module/class/upload.class.php');
		$upload = new upload;
		if ($upload->doUpload($datax, ARTICLE_IMAGE_PATH . '/' . $catIdx, ARTICLE_IMAGE_SIZE,
				'imagefile'))
		{
			$mysqlBuffer['product_image'] = $datax;
			$newImage = true;
		}
		else
		{
			message::setErrorRow(_('No Image could be uploaded.'));
			message::setErrorRow($upload->getError());
		}
	}

	// Small image
	$datax = $refValidate->cleanslash($_FILES['thumbImagefile']['name']);
	$oldSmallImagex = $refValidate->testText($_POST['oldSmallImagex'],
		_('Small article image'));

	if ($datax and ! empty($datax))
	{ // First delete old Small-Image if available
		$file = '../images/' . ARTICLE_IMAGE_PATH . '/' . $catIdx .
			'/' . ARTICLE_IMAGE_THUMB_PATH . '/' . $oldSmallImagex;

		if (!empty($oldSmallImagex) and file_exists($file))
		{
			if (unlink('../images/' . ARTICLE_IMAGE_PATH . '/' . $catIdx . '/' .
					ARTICLE_IMAGE_THUMB_PATH . '/' . $oldSmallImagex))
				message::setNoteRow(_('The old small image file was replaced successfully.'));
		}

		if (!is_dir('../images/' . ARTICLE_IMAGE_PATH))
			mkdir('../images/' . ARTICLE_IMAGE_PATH);

		if (!is_dir('../images/' . ARTICLE_IMAGE_PATH . '/' . $catIdx))
			mkdir('../images/' . ARTICLE_IMAGE_PATH . '/' . $catIdx);

		if (!is_dir('../images/' . ARTICLE_IMAGE_PATH . '/' . $catIdx .
				'/' . ARTICLE_IMAGE_THUMB_PATH))
		{
			mkdir('../images/' . ARTICLE_IMAGE_PATH . '/' . $catIdx .
				'/' . ARTICLE_IMAGE_THUMB_PATH);
		}
		include_once('module/class/upload.class.php');
		$upload = new upload;
		if ($upload->doUpload($datax,
				ARTICLE_IMAGE_PATH . '/' . $catIdx . '/' .
				ARTICLE_IMAGE_THUMB_PATH . '/', ARTICLE_IMAGE_SIZE, 'thumbImagefile'))
		{
			$mysqlBuffer['product_small_image'] = $datax;
			$newSmallImage = true;
		}
		else
		{
			message::setErrorRow(_('No Thumbnail could be uploaded.'));
			message::setErrorRow($upload->getError());
		}
	}

	// Metadescription
	$datax = $refValidate->testText($_POST['metadescriptionx'],
		_('No Metadescription indicated!'));
	if ($datax)
		$mysqlBuffer['product_metadescription'] = $datax;

	// Metakeys
	$datax = $refValidate->testText($_POST['metakeyx'], _('No Metakeywords indicated!'));
	if ($datax)
		$mysqlBuffer['product_metakey'] = $datax;

	// lastchange
	$mysqlBuffer['product_last_change'] = date("Y-m-d H:i:s");

	db::getInstance()->where("product_id", $idx);
	$result = db::getInstance()->getOne("product");

	if ($result !== NULL)
	{
		$categoryx = $refValidate->testNumber($_POST['categoryx'], _('Category-Id'), 2, 64);
		$oldcategoryx = $refValidate->testNumber($_POST['oldCategory'], _('Old Category-Id'), 2,
			64);
		$orderx = $refValidate->testNumber($_POST['orderx'], _('Order number'), 2, 64);

		if ($categoryx <> $oldcategoryx)
		{
			$countx = db::getInstance()->rawQuery("SELECT count(*) FROM product WHERE product_category ='" . $categoryx . "'");
			$count = $countx[0]['count(*)'] + 1;
			$mysqlBuffer['product_order'] = $count;
		}

		db::getInstance()->where('product_id', $idx);
		if (db::getInstance()->update('product', $mysqlBuffer))
			message::setNoteRow(_('Data successful saved.'), TRUE);

		if ($categoryx <> $oldcategoryx)
		{ // Changed Category = New ordernumbers for soure- and target-category
			$ordernr = 1;
			db::getInstance()->where("product_category", $oldcategoryx);
			db::getInstance()->orderBy('product_order', 'ASC');
			$article = db::getInstance()->get("product");

			if ($article)
			{
				foreach ($article as $valuex)
				{
					$data = Array('product_order' => $ordernr);
					db::getInstance()->where('product_id', $valuex['product_id']);
					db::getInstance()->update('product', $data);
					$ordernr++;
				}
			}

			if ((!$newImage or ! $newSmallImage or ( !$newImage and ! $newSmallImage))
				and ( !empty($oldImagex) or ! empty($oldSmallImagex)
				or ( !empty($oldImagex) and ! empty($oldSmallImagex))))
			{ // Move the images, first create dirs if not...
				if (!is_dir(ARTICLE_IMAGE_PATH))
					mkdir(ARTICLE_IMAGE_PATH);

				if (!is_dir(ARTICLE_IMAGE_PATH . '/' . $catIdx))
					mkdir(ARTICLE_IMAGE_PATH . '/' . $catIdx);

				if (!is_dir(ARTICLE_IMAGE_PATH . '/' . $catIdx .
						'/' . ARTICLE_IMAGE_THUMB_PATH))
					mkdir(ARTICLE_IMAGE_PATH . '/' . $catIdx .
						'/' . ARTICLE_IMAGE_THUMB_PATH);

				if ($newImage)
				{ // delete old Image
					if (unlink(ARTICLE_IMAGE_PATH . '/' . $oldcategoryx . '/' .
							$oldImagex))
						message::setNoteRow(_('The old image file was replaced successfully.'));
				}
				else
				{
					db::getInstance()->where("product_id", $idx);
					$art = db::getInstance()->getOne("product");

					if (rename(ARTICLE_IMAGE_PATH . '/' . $oldcategoryx .
							'/' . $oldImagex, ARTICLE_IMAGE_PATH . '/' . $categoryx .
							'/' . $oldImagex))
					{ // TODO: Delete Dirs if empty ???
						/* rmdir(ARTICLE_IMAGE_PATH . '/' . $art->product_category); */
						message::setNoteRow($art->product_id . ' ' . $art->product_name . '->' .
							_('The image file was moved successfully. '));
					}
				}

				if ($newSmallImage)
				{ // delete old Small Image
					if (unlink(ARTICLE_IMAGE_PATH . '/' . $oldcategoryx . '/' .
							ARTICLE_IMAGE_THUMB_PATH . '/' . $oldSmallImagex))
						message::setNoteRow(_('The old small image file was replaced successfully.'));
				}
				else
				{
					db::getInstance()->where("product_id", $idx);
					$art = db::getInstance()->getOne("product");

					if (rename(ARTICLE_IMAGE_PATH . '/' . $oldcategoryx .
							'/' . ARTICLE_IMAGE_THUMB_PATH . '/' . $oldSmallImagex,
							ARTICLE_IMAGE_PATH . '/' . $categoryx .
							'/' . ARTICLE_IMAGE_THUMB_PATH . '/' . $oldSmallImagex))
					{
						// TODO: Delete Dirs if empty ???
						/* rmdir(ARTICLE_IMAGE_PATH . '/' . $art->product_category); */
						message::setNoteRow($art->product_id . ' ' . $art->product_name . '->' .
							_('The small image file was moved successfully. '));
					}
				}
			}
		}
	}
	else
	{
		message::setErrorRow(_('Data coud not save!') . '->' . $artNamex, true);
	}

	if (message::ifErrorMessage())
	{
		message::setErrorRow(_('A fault is data store this one appeared!') .
			'<br> ' . _('Articlename') . ': ' . $artNamex, true);
		$refPage->addtpl('content', '/' . $page . '/' . $subpage . '.editor.tpl.php');
	}
}
?>